package QianFeng10.URLDemo;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * URL
 * 1、URL概述
 * URL(uniform resource location )类URL代表一个统一资源定位符，它是指向互联网“资源”的指针。
 * 抽象类URLConnection是所有类的超类，它代表应用程序和URL之间的通信链接。
 * <p>
 * 案例：从网络中下载文件
 **/
public class URLDownload {
    public static void main(String[] args) {
        //URL常用方法
        try {
            URL mm = new URL("http://www.baidu.com");
            //?后面表示参数  #后面表示锚点
            URL url = new URL(mm, "/index.html?username=tom#test");
            System.out.println("协议:" + url.getProtocol());
            System.out.println("主机:" + url.getHost());
            //如果未指定端口号，则使用默认端口号，getPort（）方法返回值为-1
            System.out.println("端口号:" + url.getPort());
            System.out.println("文件路径：" + url.getPath());
            System.out.println("文件名称：" + url.getRef());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        //下载一张网上的图片
        try {
            URL url = new URL("https://desk-fd.zol-img.com.cn/t_s1920x1080c5/g6/M00/05/0A/ChMkKmBSsZyIIafDACcugHv9X4wAALoxABiuT8AJy6Y419.jpg");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("F:\\Test\\cat.jpg"));
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes, 0, len);
                out.flush();
            }
            in.close();
            out.close();
            System.out.println("下载成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
